package com.cwt_taxi_xa.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.ErrorCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;

import com.cwt_taxi_xa.MainApplication;
import com.cwt_taxi_xa.constants.ConstantsAram;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.protocol.DeviceBiz;
import com.cwt_taxi_xa.protocol.DispatchCenterUsers;
import com.cwt_taxi_xa.protocol.Encoder;
import com.cwt_taxi_xa.protocol.MCUUtil;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.BitmapUtils;
import com.cwt_taxi_xa.util.GPSUtil;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.TTsFunction;
import com.cwt_taxi_xa.util.ToastUtils;
import com.cwt_taxi_xa.util.Tools;
import com.cwt_taxi_xa.util.VolumeControl;
import com.cwt_taxi_xa.util.baidu.FaceMatch;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.hobot.nebula.masklib.HobotMaskSdk;
import com.hobot.nebula.masklib.HobotMaskSdkV2;
import com.hobot.nebula.masklib.ReqCallback;
import com.hobot.nebula.masklib.ReqCallbackV2;
import com.hobot.nebula.masklib.Signer;
import com.hobot.nebula.masklib.model.MaskErrorResult;
import com.hobot.nebula.masklib.model.MaskResult;
import com.hobot.nebula.masklib.modelv2.FaceInfoV2;
import com.hobot.nebula.masklib.modelv2.MaskResultV2;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 目前用于数人头，启动集打开一个2*2像素的悬浮窗，放上一个sv，等要拍照的时候再创建camera，用完即释放
 * <p>
 * Created by ZQX on 2017/8/3 10:15
 */

public class FloatService extends Service {

    public static String APP_KEY = "2mCQVfQinOhFtB5O9mYukoG8";
    public static String APP_SECRET = "49637tSKa6SwPRQYJfxLoIsNY536Nj4Z";
    static String TAG = "FloatService";

    public static int peopleNumber = 0;

    /**
     * 上传原因
     * 0 = 平台指令
     * 1 = 空转重
     * 2 = 评价
     * 3 = 报警
     * 4 = 签到
     */
    public static int sendpictype = 0;

    public static boolean isGetPicFinish = true;

    /**
     * 郑工dvr指令
     * 获取照片
     * 协议格式(小端字节序):
     * 4bytes 包头, 固定为$A#V
     * 2bytes 命令字
     * 2bytes 序列号
     * 1bytes 版本号, 暂时为1
     * 1bytes 保留
     * 6bytes 设备唯一标识, 一般是手机号的bcd码
     * 4bytes 长度, 不包含自身
     * ? bytes 内容, 由长度确定, 可以为空
     */
    byte[] data_pic = Tools.parseHexStr2Byte("24 41 23 56 " +
            "32 00 " +
            "04 00 " +
            "01 " +
            "00 " +
            "01 87 18 51 87 25 " +
            "10 00 00 00 " +
            "01 00 00 00 " +
            "00 " +
            "05 " +
            "00 " +
            "00 00 00 00 00 00 00 00 00 ");
    long nowThread = 0;
    Socket socket_dvr_zg;
    InputStream ins_dvr_zg;
    OutputStream outs_dvr_zg;

    public void getPic(int chn) {
        isGetPicFinish = false;
        nowpicindex = chn;
        data_pic[20] = (byte) chn;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    nowThread = System.currentTimeMillis();
                    Log.e("DVR测试", "tcp链接");
                    socket_dvr_zg = new Socket(SPConstants.SPV_dvrip_zg, 9801);
                    Log.e("DVR测试", "tcp链接成功");
                    ins_dvr_zg = socket_dvr_zg.getInputStream();
                    Log.e("DVR测试", "获取输入流成功");
                    outs_dvr_zg = socket_dvr_zg.getOutputStream();
                    Log.e("DVR测试", "获取输出流成功");


                    //发出指令
                    outs_dvr_zg.write(data_pic);
                    outs_dvr_zg.flush();
                    Log.e("向DVR写出数据", Tools.parseByte2HexStr(data_pic));


                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            long thisThreadTime = nowThread;
                            byte[] buffer = new byte[512];
                            int size;
                            while (thisThreadTime == nowThread) {
                                if (System.currentTimeMillis() - thisThreadTime > 1000 * 10) {
                                    break;
                                }
                                try {
                                    size = ins_dvr_zg.read(buffer);
                                    CommotNALU(buffer, size);
                                } catch (Exception e) {
                                    Log.e("DVR测试", "读输入流线程出错-" + thisThreadTime);
                                    continue;
                                }
                            }
                        }

                    }).start();
                    Log.e("DVR测试", "启动读数据线程");

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("DVR测试", "出错");
                }
                Log.e("DVR测试", "外层连接线程结束------------------------");
            }
        }).start();
    }

    String biaoshi = "244123563280";
    String str_buffer;
    int filesize_write = 0;
    byte[] picresult;

    private void CommotNALU(byte[] result, int size) {
        if (filesize_write == 0) {
            str_buffer = Tools.parseByte2HexStr(Tools.byteTobyte(result, 0, size));
            if (str_buffer.contains(biaoshi)) {
                int startindex = str_buffer.indexOf(biaoshi);
                if (startindex > size - 36) return;
                filesize_write = getLength(str_buffer.substring(32 + startindex, 40 + startindex)) - 16;
                picresult = new byte[filesize_write];
                System.arraycopy(Tools.parseHexStr2Byte(str_buffer.substring(40 + startindex + 32)), 0, picresult, 0, size - startindex - 36);
                filesize_write -= (size - startindex - 36);
            }
        } else {
            try {
                if (size <= filesize_write) {
                    System.arraycopy(result, 0, picresult, picresult.length - filesize_write, size);
                    filesize_write -= size;
                } else {
                    System.arraycopy(result, 0, picresult, picresult.length - filesize_write, filesize_write);
                    filesize_write = 0;
                }
                if (filesize_write == 0) {
                    nowThread = 0;
                    outs_dvr_zg.close();
                    ins_dvr_zg.close();
                    socket_dvr_zg.close();
                    AppLog.e("获取照片结束");
                    isGetPicFinish = true;

//					File f;
//					FileOutputStream fos;
//					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
//					try {
//						f = new File("/mnt/sdcard/APP-PIC_test.jpg");
//						if(f.exists()) f.delete();
//						fos = new FileOutputStream(f);
//						fos.write(picresult);
//						fos.flush();
//						fos.close();
//					} catch (Exception e) {
//						e.printStackTrace();
//					}

                    switch (type) {
                        case 1:
                            if (nowpicindex == 1) {
                                pic_1 = picresult;
//							pic_1 = FileUtil.readFileByBytes("/mnt/sdcard/testqianpai.png");
                                getPic(2);
                            } else {
                                pic_2 = picresult;
                                checkMan();
                            }
                            break;
                        case 2:
                            sendPic(picresult);
                            break;
                        case 3:
//							BitmapUtils.getBitmapFromByte(picresult);
//							Bitmap bitmap = BitmapFactory.decodeByteArray(picresult, 0, picresult.length);
//							pic_3 = BitmapUtils.bitmapToNv21(bitmap,w,h);
                            pic_3 = picresult;
                            checkMaskAndFace();
                            break;

                        case 4:
                            savePic(picresult);
                            break;
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void savePic(byte[] picresult) {
        if (picresult != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(picresult, 0, picresult.length);
            String today = new SimpleDateFormat("yyMMdd").format(new Date());
//            File dayFile = new File("mnt/sdcard/" + "CWTPicFile/" + today);
//            if (dayFile.exists()) {
//                dayFile.delete();
//                dayFile.mkdir();
//            }
            File f = new File("mnt/sdcard/" + "CWTPicFile/" + today + "/" + System.currentTimeMillis() + ".jpg");
            if(!f.getParentFile().exists()){
                f.getParentFile().mkdirs();
            }
            try {
                FileOutputStream out = new FileOutputStream(f);
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String sign(String httpMethod, String httpApi) {
        try {
            SortedMap<String, String> headers = new TreeMap();
            SortedMap<String, String> params = new TreeMap();
            headers.put("content-type", "application/json");
            headers.put("host", "openapi.perf.fd.horizon.ai");
            Signer signer = new Signer(APP_KEY, APP_SECRET);
            return signer.Sign(httpMethod, httpApi, params, headers);
        } catch (Exception var5) {
            Log.e("HobotMaskSdk", "sign exception:" + var5.getMessage());
            var5.printStackTrace();
            return null;
        }
    }

    private void checkMaskAndFace() {
        AppLog.e("w= " + w);
        AppLog.e("h= " + h);
        AppLog.e("pic3= " + Tools.bytesToHexString(pic_3));


        String sData = Base64.encodeToString(pic_3, 2);
        JsonObject imageData = new JsonObject();
        imageData.addProperty("image_type", 1);
        imageData.addProperty("image_base64", sData);
        imageData.addProperty("attributes", "mask");
        OkHttpClient okHttpClient = new OkHttpClient();
        String sign = sign("POST", "/openapi/v1/faces/detect");
        RequestBody body = MultipartBody.create(MediaType.parse("application/json"), imageData.toString().getBytes());
        Request request = (new Request.Builder()).url("http://openapi.perf.fd.horizon.ai/openapi/v1/faces/detect?authorization=" + sign).post(body).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                Log.e("HobotMaskSdk", "Failure" + e.getMessage());
                ToastUtils.showToast(e.getMessage());
            }

            public void onResponse(Call call, Response response) throws IOException {
                String resultString = response.body().string();
                Log.e("HobotMaskSdk", "Success" + resultString);
                MaskResultV2 result = (MaskResultV2) (new Gson()).fromJson(resultString, MaskResultV2.class);
                if (result != null && result.getCode() == 0 && result.getMaskDataV2() != null && result.getMaskDataV2().getFaceInfoV2List() != null && result.getMaskDataV2().getFaceInfoV2List().size() > 0) {
                    if (callback != null) {
                        int faceCunt = result.getMaskDataV2().getFaceInfoV2List().size();
                        AppLog.e("FaceCount= " + faceCunt);
                        int maskCount = 0;
                        Iterator var6 = result.getMaskDataV2().getFaceInfoV2List().iterator();

                        while (var6.hasNext()) {
                            FaceInfoV2 faceInfoV2 = (FaceInfoV2) var6.next();
                            if (faceInfoV2.getMask() > 0) {
                                ++maskCount;
                            }
                        }
                        final String text = "人脸个数：" + faceCunt + ", 戴口罩人数：" + maskCount;

                        AppLog.e("MASK", text);

                        if (maskCount != faceCunt) {
                            ToastUtils.showToast(text);
                            TTsFunction.speakText("请佩戴口罩");
                            ConstantsAram.setAlarmStateValue(30, 1);
                        } else {
                            ConstantsAram.setAlarmStateValue(30, 0);
                        }

                    }
                }
//				else if (callback != null) {
//					MaskErrorResult maskErrorResult = new MaskErrorResult();
//					maskErrorResult.setErrorCode(result.getCode());
//					maskErrorResult.setErrorMsg(result.getMessage());
//					callback.onError(maskErrorResult);
//				}

            }
        });
    }

    //		HobotMaskSdkV2.feedData(pic_3, ImageFormat.NV21, w, h, new ReqCallbackV2() {
//
//
//
//			@Override
//			public void onSuccess(MaskResultV2 maskResultV2) {
//				int faceCunt = maskResultV2.getFaceCount();
//				int maskCount = maskResultV2.getMaskCount();
//				final String text = "人脸个数：" + faceCunt + ", 戴口罩人数：" + maskCount;
//
//				AppLog.e("MASK", text);
//				ToastUtils.showToast(text);
//				TTsFunction.speakText(text);
//				if (maskCount != faceCunt){
//					ConstantsAram.setAlarmStateValue(30, 1);
//				}else{
//					ConstantsAram.setAlarmStateValue(30, 0);
//				}
//			}
//
//			@Override
//			public void onError(MaskErrorResult maskErrorResult) {
//				AppLog.e("maskErrorResult", "Mask checking failed: " + maskErrorResult.getErrorMsg());
//				if (null != maskErrorResult) {
//					AppLog.e("maskErrorResult", "Mask checking failed: " + maskErrorResult.getErrorMsg());
//					ToastUtils.showToast(maskErrorResult.getErrorMsg());
//				}
//			}
//		});
//	}
    public static int getLength(String l) {
        return Integer.parseInt(l.substring(0, 2), 16) + (Integer.parseInt(l.substring(2, 4), 16) * 256) + (Integer.parseInt(l.substring(4, 6), 16) * 256 * 256)
                + (Integer.parseInt(l.substring(6, 8), 16) * 256 * 256 * 256);
    }

    int nowpicindex = 0;//专用于双路数人头,1为单路数人头
    static byte[] pic_1 = null;//前排摄像头
    static byte[] pic_2 = null;//后排摄像头
    static byte[] pic_3 = null;

    public static void checkMan() {
//		TTsFunction.speakText("正在校验");
        new Thread(new Runnable() {
            @Override
            public void run() {
                long chaoshi = System.currentTimeMillis();
                String str1 = FaceMatch.detect(pic_1);
                String str2 = FaceMatch.detect(pic_2);
                if (System.currentTimeMillis() - chaoshi > 10000) {
                    return;
                }
                AppLog.e(TAG, "NumberOfPeople checkMan str1:" + str1);
                AppLog.e(TAG, "NumberOfPeople checkMan str2:" + str2);
                try {
                    int renlian = 0;
                    JSONObject json = new JSONObject(str1);
                    int code = json.getInt("error_code");
                    if (code == 0) {
                        json = json.getJSONObject("result");
                        //renlian += json.getInt("face_num");
                        JSONArray js = json.getJSONArray("face_list");
                        for (int i = 0; i < js.length(); i++) {
                            json = js.getJSONObject(i);
                            json = json.getJSONObject("location");
                            int w = json.getInt("width");
                            AppLog.d(TAG, "NumberOfPeople checkMan 筛选前排人脸---阈：>" + getThreshold() + "----当前人脸大小：" + w);//225
                            if (w > getThreshold()) {//------------------------------------前排人脸筛选阈值
                                renlian++;
                            }
                        }
                        //前排乘客
                        if (renlian > 1) {
                            renlian = 1;//前排乘客最多1人
                        } else {
                            renlian = 0;//去除司机
                        }
                    }
                    json = new JSONObject(str2);
                    code = json.getInt("error_code");
                    if (code == 0) {
                        json = json.getJSONObject("result");
                        renlian += json.getInt("face_num");
                    }
                    if (renlian > 0) {
                        peopleNumber = renlian;
                        AppLog.d(TAG, "NumberOfPeople checkMan 校验结束，当前车内" + renlian + "人");
//						TTsFunction.speakText("校验结束，当前车内"+renlian+"人");
                    } else {
                        peopleNumber = 0;
                        AppLog.e(TAG, "NumberOfPeople checkMan 未检测到人脸");
//						TTsFunction.speakText("未检测到人脸");
                    }
                    MCUUtil.mVehicleInformation.softWareMeter.setTotalPeople(peopleNumber);
                } catch (Exception e) {
                    e.printStackTrace();
//					TTsFunction.speakText("检测失败");
                    AppLog.e(TAG, "checkMan 未检测到人脸");
                }
            }
        }).start();
    }


    //通立
    public static void onTLPIC(byte[] data) {

        File f;
        FileOutputStream fos;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        try {
            f = new File("/mnt/sdcard/APP-PIC_test.jpg");
            if (f.exists()) f.delete();
            fos = new FileOutputStream(f);
            fos.write(data);
            fos.flush();
            fos.close();
            AppLog.e("拍照结束");
        } catch (Exception e) {
            e.printStackTrace();
        }

        switch (type) {
            case 1:
                if (DvrService.nowpicindex == 2) {
                    pic_1 = data;
//				pic_1 = FileUtil.readFileByBytes("/mnt/sdcard/testqianpai.png");
                    DvrService.getInstance().sendPICOrder(3);
                } else {
                    pic_2 = data;
                    checkMan();
                }
                break;
            case 2:
                sendPic(data);
                break;
        }
    }


    public static String action_camera = "com.cwt_taxi_xa_camera.check";

    WindowManager mWindowManager;
    WindowManager.LayoutParams params;

    SurfaceView sv;
    SurfaceHolder holder;

    Camera camera;
    Camera.Parameters parameters;

    MediaRecorder mMediaRecorder;

    PictureCallback callback;

    View showView;

    boolean run = false;

    static int type = 0;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1001) {
                camera.stopPreview();
                camera.release();
                camera = null;
                run = false;
            } else if (msg.what == 1002) {
                VolumeControl.playSound();
                camera.takePicture(null, null, callback);
            } else if (msg.what == 1003) {
                sv.callOnClick();
            }
        }
    };


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    public static int seq;
    public static int channelId;
    public static int w;
    public static int h;
    int count_pt;
    int timeInterval;
    public static boolean waitUplod = true;

    @Override
    public void onCreate() {
        super.onCreate();
        initWM();
        initView();
        mWindowManager.addView(showView, params);

        callback = new PictureCallback() {
            @Override
            public void onPictureTaken(final byte[] arg0, Camera arg1) {
                switch (type) {
                    case 1:
                        TTsFunction.speakText("正在校验");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                String str = FaceMatch.detect(arg0);
                                AppLog.e(str);
                                try {
                                    JSONObject json = new JSONObject(str);
                                    int code = json.getInt("error_code");
                                    if (code == 0) {
                                        json = json.getJSONObject("result");
                                        int num = json.getInt("face_num");
                                        TTsFunction.speakText("校验结束，当前车内" + num + "人");
                                    } else {
                                        TTsFunction.speakText("未检测到人脸");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    TTsFunction.speakText("未检测到人脸");
                                }
                            }
                        }).start();
                        break;
                    case 2:
                        sendPic(arg0);
                        break;
                }

                handler.sendEmptyMessage(1001);
            }
        };


        IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction(action_camera);

        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent intent) {

                //目的      1-数人头                     2-抓拍上传平台
                type = intent.getIntExtra("type", 0);
                AppLog.d(TAG, "registerReceiver type:" + type);
                /**
                 * 先判断照片获取方式
                 * 对应的设备是否正常
                 */
                if (SPConstants.takePicFromUSB) {


                    /**
                     * 系统版本不同，usb设备数量不同！！！！！！！！！！！！！！！！
                     */
                    HashMap<String, UsbDevice> deviceHashMap = ((UsbManager) getSystemService(USB_SERVICE)).getDeviceList();
                    if (deviceHashMap.size() < 3) {
//						TTsFunction.speakText("摄像头未连接");
//						Toast.makeText(MainApplication.getInstance(), "摄像头未连接", 1000).show();
                        return;
                    }

                    switch (type) {
                        case 1://翻牌后数人头
                            if (!run) {
                                AppLog.d(TAG, "usb 确认驾驶员和乘客");
                                //TTsFunction.speakText("确认驾驶员和乘客");
                                run = true;
                                try {
                                    camera = Camera.open(0);
                                    camera.setErrorCallback(new ErrorCallback() {
                                        @Override
                                        public void onError(int arg0, Camera arg1) {
                                            handler.sendEmptyMessageDelayed(1003, 1000);
                                        }
                                    });
                                    camera.setPreviewDisplay(holder);
                                    camera.startPreview();
                                    handler.sendEmptyMessageDelayed(1002, 3000);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    run = false;
                                }
                            }
                            break;
                        case 2://平台要求抓拍
                            seq = intent.getIntExtra("seq", 0);
                            channelId = intent.getIntExtra("channelId", 0);
                            w = intent.getIntExtra("w", 0);
                            h = intent.getIntExtra("h", 0);
                            count_pt = intent.getIntExtra("count", 0);
                            timeInterval = intent.getIntExtra("timeInterval", 0);

                            if (!run) {
                                run = true;
                                try {
                                    camera = Camera.open(0);
                                    camera.setErrorCallback(new ErrorCallback() {
                                        @Override
                                        public void onError(int arg0, Camera arg1) {
                                            handler.sendEmptyMessageDelayed(1003, 1000);
                                        }
                                    });
                                    parameters = camera.getParameters();

                                    //获取预览的各种分辨率
                                    List<Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
                                    for (Size s : supportedPreviewSizes) {
                                        AppLog.e(s.width + "-----------" + s.height);
                                        if (s.width == 1280) {
//									parameters.setPreviewSize(1280, 720);
                                            parameters.setPictureSize(1280, 720);
                                        }
                                    }

                                    camera.setParameters(parameters);
                                    camera.setPreviewDisplay(holder);
                                    camera.startPreview();
                                    handler.sendEmptyMessageDelayed(1002, 3000);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    run = false;
                                }
                            }
                            break;
                    }
                } else {

                    //等dvr透传好了添加链接状态判断---------------------------------
                    //等dvr透传好了添加链接状态判断---------------------------------
                    //等dvr透传好了添加链接状态判断---------------------------------
                    //等dvr透传好了添加链接状态判断---------------------------------
                    switch (type) {
                        case 1://翻牌后数人头
//						TTsFunction.speakText("确认驾驶员和乘客");
                            AppLog.d(TAG, "确认驾驶员和乘客");
                            if (SPUtils.getParamInteger(SPConstants.SPK_dvr, SPConstants.SPV_dvr) == 1) {
                                DvrService.getInstance().sendPICOrder(2);
                            } else {
                                getPic(1);
                            }
                            break;
                        case 2://平台要求抓拍
                            seq = intent.getIntExtra("seq", 0);
                            channelId = intent.getIntExtra("channelId", 0);
                            w = intent.getIntExtra("w", 0);
                            h = intent.getIntExtra("h", 0);
                            count_pt = intent.getIntExtra("count", 0);
                            timeInterval = intent.getIntExtra("timeInterval", 0);
                            AppLog.d(TAG, "registerReceiver seq:" + seq + " channelId:" + channelId + " count_pt:" + count_pt + " timeInterval:" + timeInterval + " w:" + w + " h:" + h);
                            if (SPUtils.getParamInteger(SPConstants.SPK_dvr, SPConstants.SPV_dvr) == 1) {
                                DvrService.getInstance().sendPICOrder(channelId);
                            } else {
                                getPic(channelId - 1);
                            }
                            break;
                        case 3://拍张图片传给地平线sdk，用于检测当前人头数和口罩数
                            AppLog.d(TAG, "确认当前人头数和口罩数是否一致");
                            w = intent.getIntExtra("w", 0);
                            h = intent.getIntExtra("h", 0);
                            if (SPUtils.getParamInteger(SPConstants.SPK_dvr, SPConstants.SPV_dvr) == 1) {
                                DvrService.getInstance().sendPICOrder(2);
                            } else {
                                int maskChannel = SPUtils.getParamInteger(SPConstants.SPK_MASK_CAMERA, 2);
                                getPic(maskChannel - 1);
                            }
                            break;
                        case 4://空转重，重转空时拍两张图片存本地
                            seq = intent.getIntExtra("seq", 0);
                            w = intent.getIntExtra("w", 0);
                            h = intent.getIntExtra("h", 0);

                            for (int i = 1; i < 3; i++) {
                                if (isGetPicFinish) {
                                    getPic(i);
                                } else {
                                    i--;
                                }
                            }


                            break;
                    }

                }


            }
        }, intentFilter);


    }


    /**
     * 上传图片
     */
    public static void sendPic(final byte[] picdata) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    /**
                     * 车牌
                     * 时间
                     * 坐标
                     */
                    int mediaId = getPicId();
//					byte[] arg0111 =  FileUtil.readFileByBytes("/mnt/sdcard/画板.png");
//					byte[] photo =  FileUtil.readFileByBytes("/mnt/sdcard/tttttttt.png");
//					byte[] photo = arg0;
                    byte[] data = imageScale(picdata, w, h);
                    if (data == null) {
                        AppLog.e("上传失败");
                        return;
                    }
                    byte[] bitdata = AddTimeWatermark(compressImage(data));

//					if(seq==2222){
//
//						File f = new File("/mnt/sdcard/"+new Date().getTime()+"test.jpg");
//						FileOutputStream fos = new FileOutputStream(f);
//						fos.write(bitdata);
//						fos.flush();
//						fos.close();
//						return;
//					}

                    byte[] head = Encoder.getPicHeat(mediaId, bitdata.length);
                    byte[] photo = new byte[bitdata.length + head.length];
                    System.arraycopy(head, 0, photo, 0, head.length);
                    System.arraycopy(bitdata, 0, photo, 128, bitdata.length);
//					byte[] head = null;
                    // 总包数
                    int pkgCount;
                    // 最后一包的长度
                    int lastLen;
                    if (photo.length % 512 == 0) {
                        pkgCount = photo.length / 512;
                        lastLen = 512;
                    } else {
                        pkgCount = photo.length / 512 + 1;
                        lastLen = photo.length % 512;
                    }
                    for (int i = 0; i < pkgCount; i++) {
                        // 第几包的长度
                        int pkgLen = 512;
                        // 照片数据的最后一包
                        if (i == pkgCount - 1) {
                            pkgLen = lastLen;
                        }
                        // 分包数据
                        byte[] subData = new byte[pkgLen];
                        System.arraycopy(photo, 512 * i, subData, 0, pkgLen);
                        AppLog.i("多媒体ID:" + mediaId + "; 包总数:" + pkgCount + "; 当前第" + (i + 1) + "包");
                        DispatchCenterUsers.witeMsg(
                                Encoder.multimediaDataUpload(seq, mediaId, channelId, photo.length, 512 * i, head, subData)
                                , 0
                        );
//						waitUplod = true;
//						while(waitUplod){
//							Thread.sleep(20);
//						}
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private static byte[] compressImage(byte[] data) {
        Bitmap image = BitmapFactory.decodeByteArray(data, 0, data.length);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length > 50 * 1024) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
            if (options == 10) {
                break;
            }
        }
//    	ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
//    	Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
//    	return bitmap;
        return baos.toByteArray();
    }

//    private Bitmap getimage(String srcPath) {
//        BitmapFactory.Options newOpts = new BitmapFactory.Options();
//        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
//        newOpts.inJustDecodeBounds = true;
//        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空
//
//        newOpts.inJustDecodeBounds = false;
//        int w = newOpts.outWidth;
//        int h = newOpts.outHeight;
//        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
//        float hh = 800f;//这里设置高度为800f
//        float ww = 480f;//这里设置宽度为480f
//        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
//        int be = 1;//be=1表示不缩放
//        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
//            be = (int) (newOpts.outWidth / ww);
//        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
//            be = (int) (newOpts.outHeight / hh);
//        }
//        if (be <= 0)
//            be = 1;
//        newOpts.inSampleSize = be;//设置缩放比例
//        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
//        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
//        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
//    }

    /**
     * 调整图片大小
     *
     * @param dst_w 输出宽度
     * @param dst_h 输出高度
     * @return
     */
    public static byte[] imageScale(byte[] data, int dst_w, int dst_h) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        if (bitmap == null) {
            AppLog.e("合成bitmap失败，放弃");
            return null;
        }
        int src_w = bitmap.getWidth();
        int src_h = bitmap.getHeight();
        float scale_w = ((float) dst_w) / src_w;
        float scale_h = ((float) dst_h) / src_h;
        Matrix matrix = new Matrix();
        matrix.postScale(scale_w, scale_h);
        Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, src_w, src_h, matrix,
                true);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        dstbmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        return baos.toByteArray();
    }


    private static byte[] AddTimeWatermark(byte[] data) {
        Bitmap mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        //获取原始图片与水印图片的宽与高
        int mBitmapWidth = mBitmap.getWidth();
        int mBitmapHeight = mBitmap.getHeight();
        Bitmap mNewBitmap = Bitmap.createBitmap(mBitmapWidth, mBitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas mCanvas = new Canvas(mNewBitmap);
        //向位图中开始画入MBitmap原始图片
        mCanvas.drawBitmap(mBitmap, 0, 0, null);
        //添加文字
        Paint mPaint = new Paint();
        String mFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEEE").format(new Date());
        mFormat += ("  " + DeviceBiz.getCarNumber());
        DecimalFormat df = new DecimalFormat("#.000000");
        String location = "纬度:" + df.format(GPSUtil.getInstance().getLocInfo().getLat_f()) + "  经度:" + df.format(GPSUtil.getInstance().getLocInfo().getLng_f());
        //String mFormat = TingUtils.getTime()+"\n"+" 纬度:"+GpsService.latitude+"  经度:"+GpsService.longitude;
        mPaint.setColor(Color.RED);
        mPaint.setTextSize(15);
        //水印的位置坐标
        mCanvas.drawText(mFormat, 35, mBitmapHeight - 23, mPaint);
        mCanvas.drawText(location, 35, mBitmapHeight - 5, mPaint);
        if (FloatService.sendpictype == 1) {
            mCanvas.drawText("上车翻牌", 35, mBitmapHeight - 43, mPaint);
            FloatService.sendpictype = 0;
        } else if (FloatService.sendpictype == 2) {
            mCanvas.drawText("评价", 35, mBitmapHeight - 43, mPaint);
            FloatService.sendpictype = 0;
        } else if (FloatService.sendpictype == 3) {
            mCanvas.drawText("报警", 35, mBitmapHeight - 43, mPaint);
            FloatService.sendpictype = 0;
        } else if (FloatService.sendpictype == 4) {
            mCanvas.drawText("签到", 35, mBitmapHeight - 43, mPaint);
            FloatService.sendpictype = 0;
        }
//        mCanvas.drawText(mFormat, (mBitmapWidth * 1) / 20,(mBitmapHeight*19)/20,mPaint);
        mCanvas.save(Canvas.ALL_SAVE_FLAG);
        mCanvas.restore();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mNewBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        return baos.toByteArray();

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void initView() {
        sv = new SurfaceView(FloatService.this);
        sv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                try {
                    if (camera != null) {
                        camera.stopPreview();
                        camera.release();
                        camera = Camera.open(0);
                        camera.setPreviewDisplay(holder);
                        camera.startPreview();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        holder = sv.getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                FloatService.this.holder = holder;
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                FloatService.this.holder = holder;
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
            }
        });
        showView = sv;
    }

//    private void recorderStart(){
//        camera.unlock();
//        mMediaRecorder = new MediaRecorder();
//        mMediaRecorder.setCamera(camera);
//        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
//        mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));
//        mMediaRecorder.setPreviewDisplay(holder.getSurface());
//        try {
//            mMediaRecorder.setOutputFile(getFolderPath()+sdf.format(new Date())+".mp4");
//            mMediaRecorder.prepare();
//            mMediaRecorder.start();
//            handler.sendMessageDelayed(handler.obtainMessage(1001), 5*60*1000);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    private void recorderStop(){
//        mMediaRecorder.stop();
//        mMediaRecorder.reset();
//        mMediaRecorder = null;
//        camera.lock();
//    }

    private void initWM() {
        mWindowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        params = new WindowManager.LayoutParams();
        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.format = PixelFormat.TRANSLUCENT;
        params.width = 2;
        params.height = 2;
//        params.width = mWindowManager.getDefaultDisplay().getWidth();
//        params.height = mWindowManager.getDefaultDisplay().getHeight();
//        params.x = 100;
//        params.y = 100;
        params.gravity = Gravity.LEFT | Gravity.BOTTOM;
    }

    /**
     * 获取SD path
     */
    public String getFolderPath() {
        return Environment.getExternalStorageDirectory().toString() + "/行车记录视频/";
    }


    public static int getPicId() {
        int id = SPUtils.getParamInteger("picid", 1);
        if (id >= 256 * 256) {
            id = 1;
        } else {
            id++;
        }
        SPUtils.setParam("picid", id);
        return id;
    }

    public static int getThreshold() {
        return SPConstants.SPV_threshold_default + SPUtils.getParamInteger(SPConstants.SPK_people_threshold, SPConstants.SPV_threshold_max / 2);
    }

}
